<?php
/**
 * Application level Controller
 *
 * This file is application-wide controller file. You can put all
 * application-wide controller-related methods here.
 *
 * PHP 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       app.Controller
 * @since         CakePHP(tm) v 0.2.9
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */

App::uses('Controller', 'Controller');

/**
 * Application Controller
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @package       app.Controller
 * @link http://book.cakephp.org/2.0/en/controllers.html#the-app-controller
 */
class AppController extends Controller {
    
    public $uses = array("Organisation");
    public $components = array('Session', 'Api','Upload', 'RequestHandler', 'Cookie');
    
    public function beforeFilter() {
        parent::beforeFilter();

        if ( $this->Cookie->check('ma_session') && !$this->Session->check('member_account') ) {
            $response = $this->reactivateSession();

            if( $response['status'] == 'failed' && $this->request->here != Router::url("/") ) {
                $this->Cookie->delete('ma_session');
                $this->redirect("/");
            }
        }
        
        if( $this->Session->check('member_account') && $this->request->here == Router::url("/") ) {
            $this->redirect('/member');
        }
    }
    
    public function validateOrganisationAccount() {
        if( $this->Session->check('org_account') ) {
            $this->loadOrgSettings();
        }
        
        else {
            $this->redirect('/member/organisations');
        }
    }
    
    public function loadOrgSettings() {
        // get user authentication
        $orgAccount = $this->Session->read('org_account');

        // retrieve settings for user organisation
        $settings = $this->Api->post('/organisation/settings', array(
            'organisation_id' => $orgAccount['Organisation']['id']
        ));

        $this->set('org_settings', $settings);

        $this->fetch_notifications();
    }
    
    public function reactivateSession() {
        $cookie = $this->Cookie->read('ma_session');
        
        $response = $this->Api->post('/members/validate_session', array(
            'member_account_id' => $cookie['member_account_id'],
            'session_device_id' => $cookie['session_device_id']
        ));
        
        if( $response['status'] == "success" && $response['session_status'] == "valid" ) {
            $this->Session->write('member_account', $response['account']);

            return array('status' => 'success');
        }
        
        return array('status' => 'failed');
    }
    
    /**
     * 
     * @param type $key
     * @return type
     */
    public function getOrganisationSetting($key) {
        $orgAccount = $this->Session->read('org_account');
        
        $setting = $this->Api->post('/organisation/setting', array(
            'organisation_id' => $orgAccount['Organisation']['id'],
            'key' => $key
        ));
        
        return $setting;
    }

    public function getOrgData($field=null){
        $orgAccount = $this->Session->read('org_account');
        if($field != null){
            return $orgAccount['Organisation'][$field];
        }
        return $orgAccount;
    }

    private function fetch_notifications() {
        $orgAccount = $this->Session->read('org_account');
        
        $batch = array(
            'notifications' => array(
                'method' => 'post',
                'url' => '/organisation/notifications',
                'params' => array(
                    'organisation_id' => $orgAccount['Organisation']['id']
                )
            )
        );
        
        if( isset($this->request->query['ntf_id']) ) {
            $batch['mark_read'] = array(
                'method' => 'post',
                'url' => '/organisation/notifications/mark_read',
                'params' => array(
                    'organisation_id' => $orgAccount['Organisation']['id'],
                    'notification_id' => $this->request->query['ntf_id'],
                    'notification_type_id' => $this->request->query['ntf_grp'],
                    'read' => 1
                )
            );
        }
        
        $response = $this->Api->post('/batch', $batch);
        
        if( $response['notifications']['status'] == 'success' ) {
            $this->set('notifications', $response['notifications']['list']);
        }
        else {
            $this->set('notifications', array());
        }
    }

    function getDays()
    {
        $start = 1;
        $end = 31;
        $days_arr = array();
        for($start; $start<=$end; $start++){
            $days_arr[$start] = $start;
        }
        return $days_arr;
    }

    function getWeeks($index = null)
    {
        $start = 1;
        $end = 5;
        $week_arr = array();
        for($start; $start<=$end; $start++){
            $week_arr[$start] = 'Wk '.$start;
        }

        if($index){
            return $week_arr[$index];
        }
        else{
            return $week_arr;
        }
    }

    function getMonths($index = null)
    {
        $months = array();
        for( $i = 1; $i <= 12; $i++ ) {
            //$month_num = str_pad( $i, 2, 0, STR_PAD_LEFT );
            $month_num = $i;
            $month_name = date( 'F', mktime( 0, 0, 0, $i + 1, 0, 0, 0 ) );
            $months[$month_num]= $month_name;
        }

        if($index){
            return $months[$index];
        }
        else{
            return $months;
        }
    }

    function week_of_month($date) {
        $date_parts = explode('-', $date);
        $date_parts[2] = '01';
        $first_of_month = implode('-', $date_parts);
        $day_of_first = date('N', strtotime($first_of_month));
        $day_of_month = date('j', strtotime($date));
        return floor(($day_of_first + $day_of_month - 1) / 7) + 1;
    }

    function month_select_box( $field_name = 'month' ) {
        $month_options = '';
        for( $i = 1; $i <= 12; $i++ ) {
            $month_num = str_pad( $i, 2, 0, STR_PAD_LEFT );
            $month_name = date( 'F', mktime( 0, 0, 0, $i + 1, 0, 0, 0 ) );
            $month_options .= '<option value="' . esc_attr( $month_num ) . '">' . $month_name . '</option>';
        }
        return '<select name="' . $field_name . '">' . $month_options . '</select>';
    }




    function getYears($start = 2012, $end = 'CURRENT YEAR')
    {
        if($end == 'CURRENT YEAR' ){
            $end = date('Y');
        }
        $start = (int)$start;
        $end = (int)$end;
        $years_arr = array();
        for($start; $start<=$end; $start++){
            $years_arr[$start] = $start;
        }

        return $years_arr;
    }


}
